package com.xuelang.pipeline.app.resource.impl;

import org.springframework.cloud.client.circuitbreaker.NoFallbackAvailableException;
import java.lang.RuntimeException;
import java.util.concurrent.TimeoutException;
import com.xuelang.pipeline.app.resource.DynamicNamespaceService;
import com.xuelang.pipeline.app.resource.request.NamespaceListRequest;
import com.xuelang.pipeline.app.resource.request.NamespaceMainRequest;
import com.xuelang.pipeline.client.common.result.ApiResult;
import com.xuelang.pipeline.client.resource.dto.NamespaceDTO;
import org.springframework.cloud.openfeign.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.util.List;

/**
 * 动态命名空间服务fegin调用失败回调实现类
 *
 * @author xiwen.zxg
 * @since 2024/5/15
 */
@Slf4j
@Service
public class DynamicNamespaceServiceFallbackImpl implements FallbackFactory<DynamicNamespaceService> {


    @Override
    public DynamicNamespaceService create(Throwable throwable) {
        String fallReason = throwable.getMessage();
        if (throwable instanceof TimeoutException) {
            fallReason = "Socket connect timeout.";
        } else if (throwable instanceof NoFallbackAvailableException) {
            fallReason = "Bad Request.";
        } else if (throwable instanceof RuntimeException) {
            fallReason = "Runtime exception";
        }

        final String returnFallReason = fallReason;

        log.error("调用fegin数据接口失败。接口名称:{}；失败原因:{}", this.getClass().getName(), fallReason);
        return new DynamicNamespaceService() {

            ApiResult apiResult = ApiResult.fail("worker返回异常：" + returnFallReason);

            @Override
            public ApiResult<List<NamespaceDTO>> list(URI uri, NamespaceListRequest namespaceListRequest) {
                return apiResult;
            }

            @Override
            public ApiResult<Boolean> create(URI uri, NamespaceMainRequest namespaceMainRequest) {
                return apiResult;
            }

            @Override
            public ApiResult<Boolean> delete(URI uri, NamespaceMainRequest namespaceMainRequest) {
                return apiResult;
            }
        };
    }

}
